package com.ly.ocw.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ly.ocw.comm.MyPage;
import com.ly.ocw.entity.Vcode;
import com.ly.ocw.repository.VcodeDao;
import com.ly.ocw.utils.SDKTestSendTemplateSMS;

/**
 * 
 * 
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class VcodeService {

	private static Logger logger = LoggerFactory.getLogger(VcodeService.class);

	@Autowired
	private VcodeDao vcodeDao;

	public Vcode getById(Long id) {
		return vcodeDao.getById(id);
	}

	public List<Vcode> getAll() {
		return vcodeDao.getAll();
	}

	/**
	 * 分页查询
	 * 
	 * @param overtime
	 * @param pageStart
	 * @param pageSize
	 * @return
	 */
	public MyPage<Vcode> searchPage(Vcode vcode, int currentPage, int pageSize) {
		MyPage<Vcode> myPage = new MyPage<Vcode>();

		Long count = vcodeDao.searchCount(vcode);

		int pageStart = (currentPage - 1) < 0 ? 0 : (currentPage - 1) * pageSize;
		List<Vcode> list = vcodeDao.searchPage(vcode, pageStart, pageSize);

		myPage.setCount(count);
		myPage.setContent(list);

		return myPage;
	}

	public void save(Vcode vcode) {
		vcodeDao.save(vcode);
	}

	public void update(Vcode vcode) {
		vcodeDao.update(vcode);
	}

	/**
	 * 软删除
	 */
	public void delete(Long id) {
		vcodeDao.delete(id);
	}

	public Vcode getByPhone(String phone) {
		return vcodeDao.getByPhone(phone);
	}

	public void sendSms(String phone) {
		String strVcode = SDKTestSendTemplateSMS.getVcode();

		// 保存到数据库
		Vcode vcode = getByPhone(phone);

		if (vcode == null) {
			// 该手机号第一次发送验证码
			vcode = new Vcode();
			vcode.setCount(0L);
			vcode.setPhone(phone);
			vcode.setSendDate(new Date());
			vcode.setVcode(strVcode);

			vcodeDao.save(vcode);
		} else {
			vcode.setCount(vcode.getCount() + 1);
			vcode.setPhone(phone);
			vcode.setSendDate(new Date());
			vcode.setVcode(strVcode);

			vcodeDao.update(vcode);
		}

		// 发送短信
		SDKTestSendTemplateSMS.sendSms(phone, strVcode);
	}

	// 验证 手机验证码是否存在
	public boolean validate(String phone, String valiCode) {
		
		//演示账户
		if("15850660001".equals(phone)){
			return true;
		}
		
		Vcode vcode = vcodeDao.getByPhoneAndVcode(phone, valiCode);
		if (vcode != null) {
			return true;
		}

		return false;
	}

	public boolean validateForDev(String phone, String valiCode) {
		return true;
	}

}
